package com.snsoft.web.interceptor;

import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.snsoft.bean.User;
import com.snsoft.bean.UserSession;
import com.snsoft.dao.UserDao;
import com.snsoft.util.Constants;
import com.snsoft.util.EncodeUtils;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年12月22日 下午1:40:32
 * 
 * @Description TODO
 *    登录拦截器，用于自动登录
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserDao userDao;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("LoginInterceptor--preHandle");
		//取得浏览器的Cookie
		Cookie[] cookies = request.getCookies();
		Cookie userCookie = null;
		
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if("userInfo".equals(cookie.getName())){
					userCookie = cookie;
					break;
				}
			}
			//if found
			if(userCookie != null){
				//取出cookie信息
				String userinfo = URLDecoder.decode(userCookie.getValue(), Constants.CHARSET);
				String[] infos = userinfo.split("_");
				if(infos.length == 2 && (!StringUtils.isEmpty(infos[0])) && (!StringUtils.isEmpty(infos[1]))){
					String password = EncodeUtils.encodeByBase64(infos[1]);
					//获取用户，校验密码
					User user = userDao.getUser(infos[0]);
					if(user != null && user.getUserPassWord().equals(EncodeUtils.encodeByMd5(password))){
						//用户信息存入session
						request.getSession(true).setAttribute("userSession", 
								new UserSession(user.getUserID(), user.getUserName(), user.getRole()));
					}
				}
			}
		}
		
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

}
